import { queryUserInfo } from '@/service/user';
import cache from '@/utils/cache';
import { defineStore } from 'pinia';

interface UserSate {
  userInfos: {
    authBtnList: string[];
    photo: string;
    roles: string[];
    time: number;
    userName: string;
    [key: string]: any;
  };
  token: string | null;
  temToken: string | null;
}
export const useUserStore = defineStore({
  id: 'userStore',
  state: (): UserSate => ({
    userInfos: {
      userName: '',
      user: {},
      photo: '',
      time: 0,
      roles: [],
      authBtnList: [],
    },
    token: cache.get('token') || null,
    temToken: null,
  }),
  getters: {
    isLogin: (state) => !!state.token,
  },
  actions: {
    async getUser() {
      const res = await queryUserInfo();
      const userInfo: any = {
        userName: res.data.sysUser.nickname,
        user: res.data.sysUser,
        time: new Date().getTime(),
        roles: res.data.roles,
        authBtnList: res.data.permissions,
      };
      this.userInfos = userInfo;
    },
    storeToken(token: string) {
      this.token = token;
      cache.set('token', token);
    },
    logout() {
      this.token = '';
      this.userInfo = {};
      cache.remove('token');
    },
  },
});
